var stompClient = null;

function setConnected(connected) {
    $("#connect").prop("disabled", connected);
    $("#disconnect").prop("disabled", !connected);
    if (connected) {
        $("#conversation").show();
    }
    else {
        $("#conversation").hide();
    }
    $("#greetings").html("");
}

function connect() {
    var host = window.location.host;
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://" + host + "/webSocketIMServer?clientId=6");
    } else if ('MozWebSocket' in window) {
        websocket = new MozWebSocket("ws://" + host + "/webSocketIMServer?clientId=6");
    } else {
        websocket = new SockJS("http://" + host + "/sockjs/webSocketIMServer?clientId=6");
    }
    websocket.onopen = function(evnt) {
        console.log("websocket连接上");
        setConnected(true);
    };
    websocket.onmessage = function(evnt) {
        console.log("接收到的消息：" + evnt.data);
        showGreeting(evnt.data);
    };
    websocket.onerror = function(evnt) {
        console.log("websocket错误");
    };
    websocket.onclose = function(evnt) {
        console.log("websocket关闭");
    }
}

function disconnect() {
    if (stompClient !== null) {
        stompClient.disconnect();
    }
    setConnected(false);
    console.log("Disconnected");
}

function sendName() {
    websocket.send(JSON.stringify({'name': $("#name").val()}));
}

function showGreeting(message) {
    $("#greetings").append("<tr><td>" + message + "</td></tr>");
}

$(function () {
    $("form").on('submit', function (e) {
        e.preventDefault();
    });
    $( "#connect" ).click(function() { connect(); });
    $( "#disconnect" ).click(function() { disconnect(); });
    $( "#send" ).click(function() { sendName(); });
});

